<template>
  <div class="file-uploader" v-if="show" @click.stop>
    <div class="uploader-header">
      <span class="uploader-title">上传文件</span>
      <el-button type="text" @click="$emit('close')" class="close-btn">
        <el-icon><Close /></el-icon>
      </el-button>
    </div>
    
    <div class="uploader-content">
      <!-- 拖拽上传区域 -->
      <div 
        class="upload-area"
        :class="{ 'is-dragover': isDragOver }"
        @drop="handleDrop"
        @dragover="handleDragOver"
        @dragleave="handleDragLeave"
        @click="triggerFileInput"
      >
        <div class="upload-icon">
          <el-icon size="48"><Upload /></el-icon>
        </div>
        <div class="upload-text">
          <p>点击或拖拽文件到此处上传</p>
          <p class="upload-hint">支持图片、文档等文件</p>
        </div>
        <input
          ref="fileInput"
          type="file"
          multiple
          accept="image/*,.pdf,.doc,.docx,.txt,.md,.mp3,.wav,.mp4,.avi"
          @change="handleFileSelect"
          style="display: none"
        />
      </div>
      
      
      <!-- 上传进度 -->
      <div v-if="uploadingFiles.length > 0" class="upload-progress">
        <div 
          v-for="file in uploadingFiles" 
          :key="file.id"
          class="upload-item"
        >
          <div class="file-info">
            <el-icon class="file-icon">
              <Picture v-if="isImageFile(file.name)" />
              <Document v-else />
            </el-icon>
            <span class="file-name">{{ file.name }}</span>
            <span class="file-size">{{ formatFileSize(file.size) }}</span>
          </div>
          <div class="progress-bar">
            <el-progress 
              :percentage="file.progress" 
              :status="file.status"
              :stroke-width="4"
            />
          </div>
          <div class="file-actions">
            <el-button 
              v-if="file.status === 'success' && file.url"
              type="text" 
              size="small"
              @click="copyFileUrl(file.url!)"
            >
              复制链接
            </el-button>
            <el-button 
              v-if="file.status === 'exception'"
              type="text" 
              size="small"
              @click="retryUpload(file)"
            >
              重试
            </el-button>
          </div>
        </div>
      </div>
    </div>
    
    <div class="uploader-footer">
      <el-button @click="$emit('close')">关闭</el-button>
      <el-button 
        type="primary" 
        @click="confirmUpload"
        :disabled="uploadedCount === 0"
      >
        确认上传 ({{ uploadedCount }}/{{ uploadingFiles.length }})
      </el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { Close, Upload, Picture, Document } from '@element-plus/icons-vue'
import { fileApi } from '../../services/api'

interface Props {
  show: boolean
}

const props = defineProps<Props>()

const emit = defineEmits<{
  close: []
  uploadComplete: [files: UploadedFile[]]
}>()

interface UploadingFile {
  id: string
  name: string
  size: number
  progress: number
  status: 'uploading' | 'success' | 'exception'
  url?: string
  file: File
}

interface UploadedFile {
  name: string
  url: string
  type: string
  size: number
}

const isDragOver = ref(false)
const fileInput = ref<HTMLInputElement>()
const uploadingFiles = ref<UploadingFile[]>([])
const uploadedCount = ref(0)

// 计算属性
const hasUploadingFiles = computed(() => {
  const hasUploading = uploadingFiles.value.some(file => file.status === 'uploading')
  console.log('hasUploadingFiles 计算:', hasUploading, '文件状态:', uploadingFiles.value.map(f => f.status))
  return hasUploading
})

// 更新上传成功数量
const updateUploadedCount = () => {
  const count = uploadingFiles.value.filter(file => file.status === 'success').length
  uploadedCount.value = count
  console.log('更新 uploadedCount:', count)
  console.log('所有文件状态:', uploadingFiles.value.map(f => ({ name: f.name, status: f.status })))
}

// 文件类型判断
const isImageFile = (filename: string): boolean => {
  const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.svg']
  const ext = filename.toLowerCase().substring(filename.lastIndexOf('.'))
  return imageExtensions.includes(ext)
}

// 格式化文件大小
const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 触发文件选择
const triggerFileInput = () => {
  fileInput.value?.click()
}

// 处理文件选择
const handleFileSelect = (event: Event) => {
  const target = event.target as HTMLInputElement
  if (target.files) {
    handleFiles(Array.from(target.files))
  }
}

// 处理拖拽
const handleDragOver = (event: DragEvent) => {
  event.preventDefault()
  isDragOver.value = true
}

const handleDragLeave = (event: DragEvent) => {
  event.preventDefault()
  isDragOver.value = false
}

const handleDrop = (event: DragEvent) => {
  event.preventDefault()
  isDragOver.value = false
  
  if (event.dataTransfer?.files) {
    handleFiles(Array.from(event.dataTransfer.files))
  }
}

// 处理文件
const handleFiles = (files: File[]) => {
  // 过滤和验证文件
  const validFiles = files.filter(file => {
    // 文件大小限制 (10MB)
    if (file.size > 10 * 1024 * 1024) {
      ElMessage.error(`文件 ${file.name} 超过 10MB 限制`)
      return false
    }
    
    // 文件类型验证
    const allowedTypes = [
      'image/jpeg', 'image/png', 'image/gif', 'image/bmp', 'image/webp', 'image/svg+xml',
      'application/pdf', 'application/msword', 
      'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
      'text/plain', 'text/markdown',
      'audio/mpeg', 'audio/mp3', 'audio/wav', 'audio/ogg', 'audio/webm', 'audio/m4a',
      'video/mp4', 'video/avi', 'video/quicktime', 'video/x-msvideo'
    ]
    
    if (!allowedTypes.includes(file.type)) {
      ElMessage.error(`不支持的文件类型: ${file.name}`)
      return false
    }
    
    return true
  })
  
  // 添加到上传列表
  validFiles.forEach(file => {
    const uploadingFile: UploadingFile = {
      id: Date.now().toString() + Math.random().toString(36).substr(2, 9),
      name: file.name,
      size: file.size,
      progress: 0,
      status: 'uploading',
      file
    }
    uploadingFiles.value.push(uploadingFile)
    
    // 开始上传
    uploadFile(uploadingFile)
  })
}

// 上传文件
const uploadFile = async (uploadingFile: UploadingFile) => {
  try {
    let response
    
    if (isImageFile(uploadingFile.name)) {
      response = await fileApi.uploadImage(uploadingFile.file, 'general')
    } else {
      response = await fileApi.uploadBatchFiles([uploadingFile.file], 'general')
    }
    
    // 调试信息
    console.log('上传响应:', response)
    console.log('响应代码:', response.code)
    console.log('响应数据:', response.data)
    
    if (response.code === 200 || response.code === 0) {
      uploadingFile.progress = 100
      uploadingFile.status = 'success'
      
      // 处理不同的响应格式
      if (isImageFile(uploadingFile.name)) {
        // 图片上传响应格式
        uploadingFile.url = response.data?.file_url
      } else {
        // 批量上传响应格式
        const successfulFile = response.data?.successful_files?.[0]
        uploadingFile.url = successfulFile?.file_url
      }
      
      // 调试信息
      console.log('文件上传成功，状态更新为:', uploadingFile.status)
      console.log('当前所有文件状态:', uploadingFiles.value.map(f => ({ name: f.name, status: f.status })))
      
      // 确保状态更新后重新计算
      await nextTick()
      console.log('nextTick 后的文件状态:', uploadingFiles.value.map(f => ({ name: f.name, status: f.status })))
      
      // 更新上传成功数量
      updateUploadedCount()
      
      ElMessage.success(`${uploadingFile.name} 上传成功`)
    } else {
      throw new Error(response.message || '上传失败')
    }
  } catch (error) {
    console.error('上传失败:', error)
    uploadingFile.status = 'exception'
    uploadingFile.progress = 0
    ElMessage.error(`${uploadingFile.name} 上传失败`)
  }
}

// 重试上传
const retryUpload = (uploadingFile: UploadingFile) => {
  uploadingFile.status = 'uploading'
  uploadingFile.progress = 0
  uploadFile(uploadingFile)
}

// 复制文件链接
const copyFileUrl = async (url: string) => {
  try {
    await navigator.clipboard.writeText(url)
    ElMessage.success('链接已复制到剪贴板')
  } catch (error) {
    console.error('复制失败:', error)
    ElMessage.error('复制失败')
  }
}

// 确认上传
const confirmUpload = () => {
  console.log('确认上传被点击')
  console.log('当前文件列表:', uploadingFiles.value)
  
  const uploadedFiles: UploadedFile[] = uploadingFiles.value
    .filter(file => file.status === 'success')
    .map(file => ({
      name: file.name,
      url: file.url!,
      type: isImageFile(file.name) ? 'image' : 'file',
      size: file.size
    }))
  
  console.log('准备发送的文件:', uploadedFiles)
  
  emit('uploadComplete', uploadedFiles)
  uploadingFiles.value = []
}
</script>

<style scoped>
.file-uploader {
  position: absolute;
  bottom: 100%;
  left: 0;
  width: 400px;
  background: white;
  border: 1px solid #e5e7eb;
  border-radius: 12px;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
  z-index: 1000;
  max-height: 500px;
  display: flex;
  flex-direction: column;
}

.uploader-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid #e5e7eb;
}

.uploader-title {
  font-size: 14px;
  font-weight: 600;
  color: #374151;
}

.close-btn {
  padding: 4px;
  color: #6b7280;
}

.uploader-content {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
}

.upload-area {
  border: 2px dashed #d1d5db;
  border-radius: 8px;
  padding: 32px 16px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
  margin-bottom: 16px;
}

.upload-area:hover,
.upload-area.is-dragover {
  border-color: #3b82f6;
  background-color: #f8fafc;
}

.upload-icon {
  color: #9ca3af;
  margin-bottom: 12px;
}

.upload-text p {
  margin: 4px 0;
  color: #6b7280;
}

.upload-hint {
  font-size: 12px;
  color: #9ca3af;
}


.upload-progress {
  max-height: 200px;
  overflow-y: auto;
}

.upload-item {
  padding: 12px;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  margin-bottom: 8px;
  background: #f9fafb;
}

.file-info {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.file-icon {
  color: #6b7280;
}

.file-name {
  flex: 1;
  font-size: 14px;
  color: #374151;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.file-size {
  font-size: 12px;
  color: #9ca3af;
}

.progress-bar {
  margin-bottom: 8px;
}

.file-actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}

.uploader-footer {
  padding: 12px 16px;
  border-top: 1px solid #e5e7eb;
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}

/* 暗色主题支持 */
.dark .file-uploader {
  background: #1f2937;
  border-color: #374151;
}

.dark .uploader-title {
  color: #f9fafb;
}

.dark .upload-area {
  border-color: #4b5563;
}

.dark .upload-area:hover,
.dark .upload-area.is-dragover {
  border-color: #3b82f6;
  background-color: #111827;
}

.dark .upload-item {
  background: #111827;
  border-color: #374151;
}

.dark .file-name {
  color: #f9fafb;
}
</style>
